package com.jakewharton.rxbinding4.component;

import static com.jakewharton.rxbinding4.internal.Preconditions.checkMainThread;

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.functions.Predicate;
import io.reactivex.rxjava3.openharmony.MainThreadDisposable;
import ohos.agp.components.SearchBar;

final class SearchBarQueryChangesOnSubscribe extends Observable<String> {
    final SearchBar view;
    final Predicate<? super String> handled;

    SearchBarQueryChangesOnSubscribe(SearchBar view, Predicate<? super String> handled) {
        this.view = view;
        this.handled = handled;
    }

    @Override
    protected void subscribeActual(final Observer<? super String> observer) {
        if (!checkMainThread(observer)) {
            return;
        }
        Listener listener = new Listener(view, observer, handled);
        observer.onSubscribe(listener);
        view.setQueryListener(listener);
    }

    static final class Listener extends MainThreadDisposable implements SearchBar.QueryListener {
        final SearchBar view;
        final Observer<? super String> observer;
        private final Predicate<? super String> handled;

        Listener(SearchBar view, Observer<? super String> observer, Predicate<? super String> handled) {
            this.view = view;
            this.observer = observer;
            this.handled = handled;
        }

        @Override
        protected void onDispose() {
            view.setQueryListener(null);
        }

        @Override
        public boolean onQuerySubmit(String query) {
            return false;
        }

        @Override
        public boolean onQueryChanged(String query) {
            if (!isDisposed()) {
                try {
                    if (handled.test(query)) {
                        observer.onNext(query);
                        return true;
                    }
                } catch (Throwable e) {
                    observer.onError(e);
                    dispose();
                }
            }
            return false;
        }
    }
}
